﻿using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace FinalYear.iNavigate.Classes
{
    /// <summary>
    /// Equation of the line between a point in frame T and T + 1
    /// </summary>
    public class LineEquation
    {
        public int gradient { get; set; }

        public int intersect { get; set; }

        public PointF startPoint { get; set; }

        public PointF endPoint { get; set; }
    }

    public class LineEquations : List<LineEquation>
    {
        private List<LineEquation[]> array;

        public PointF FOE()
        {
            this.array = new List<LineEquation[]>();
            Dictionary<PointF, int> frequency = new Dictionary<PointF, int>();

            // take two lines each from the list and compare them and calculate the match point.
            // for the first line
            for (int i = 0; i < this.Count(); i++)
            {
                // for the second line
                for (int j = 0; j < this.Count(); j++)
                {
                    LineEquation[] array = new LineEquation[2];
                    array[0] = this[i];
                    array[1] = this[j];

                    // check if the lines are not the same
                    if ((this[j] != this[i]) && (this.Comparer(array) == false))
                    {
                        PointF p1 = new PointF();
                        int sumOfGradients = -(this[i].gradient - this[j].gradient);
                        p1.X = (sumOfGradients != 0) ? this[i].intersect - this[j].intersect / sumOfGradients : sumOfGradients;
                        p1.Y = this[i].gradient * p1.X + this[i].intersect;

                        if (frequency.Count() > 0)
                        {
                            if (frequency.ContainsKey(p1))
                            {
                                frequency[p1] = frequency[p1]++;
                            }
                            else
                            {
                                frequency.Add(p1, 1);
                            }
                        }
                        else
                        {
                            frequency.Add(p1, 1);
                        }

                        this.array.Add(array);
                    }
                }
            }

            return new PointF();
        }

        public bool Comparer(LineEquation[] arr)
        {
            int count = 0;
            for (int i = 0; i < this.array.Count; i++)
            {
                if (arr[0] == this.array[i][0] || arr[0] == this.array[i][1] || arr[1] == this.array[i][0] || arr[1] == this.array[i][1])
                {
                    count++;
                }
            }

            if (count == 2)
            {
                return true;
            }

            return false;
        }
    }
}